package conf

import (
	"flag"
	"fmt"
	"os"
	"time"

	"github.com/nsqio/go-nsq"
	"github.com/spf13/viper"

	"gsms/pkg/orm"
)

// Tag
var (
	Conf       = &Config{}
	configFile string
)

// Config 配置
type Config struct {
	ORM            *orm.Config     `mapstructure:"orm"`
	HTTP           *HTTP           `mapstructure:"http"`
	NSQ            *nsq.Config     `mapstructure:"nsq"`
	NSQAddr        *NSQAddr        `mapstructure:"nsq_conf"`
	SMS            *SMS            `mapstructure:"sms"`
	AllowedServers *AllowedServers `mapstructure:"allowed_servers"`
}

// NSQ 定时任务配置
type NSQAddr struct {
	NSQAddress    string `mapstructure:"nsq_address"`
	LookupAddress string `mapstructure:"lookup_address"`
}

// HTTP 服务端口配置
type HTTP struct {
	Port    string `mapstructure:"port"`
	RpcPort string `mapstructure:"rpc_port"`
}

// HTTP 服务端口配置
type SMS struct {
	VendorName       string `mapstructure:"vendor_name"`
	APIKey           string `mapstructure:"api_key"`
	RegionId         string `mapstructure:"region_id"`
	AccessKeyId      string `mapstructure:"access_key_id"`
	AccessKeySecret  string `mapstructure:"access_key_secret"`
	SignName         string `mapstructure:"sign_name"`
	TemplateIDVerify string `mapstructure:"template_id_verify"`
}

// 允许使用的服务
type AllowedServers struct {
	Names []string `mapstructure:"names"`
}

func (a *AllowedServers) IsAllowed(name string) bool {
	for _, n := range a.Names {
		if n == name {
			return true
		}
	}
	return false
}

// NewConfig new config
func NewConfig() *Config {
	NSQ := nsq.NewConfig()
	NSQ.MaxInFlight = 5
	NSQ.MsgTimeout = 3 * time.Second
	// 默认设置
	return &Config{
		ORM: &orm.Config{
			DSN:         "host=127.0.0.1 port=5432 user=postgres dbname=gsms password=newman123 sslmode=disable",
			Active:      5,
			Idle:        5,
			IdleTimeout: time.Hour * 4,
		},
		HTTP: &HTTP{
			Port:    ":8999",
			RpcPort: ":7777",
		},
		NSQ: NSQ,
		NSQAddr: &NSQAddr{
			NSQAddress:    "10.0.244.37:4150",
			LookupAddress: "10.0.244.37:4161",
		},
		SMS: &SMS{
			VendorName:       "",
			APIKey:           "56537f3adf115f1ae5df544070aa339d",
			RegionId:         "cn-hangzhou",
			AccessKeyId:      "LTAI4GDBKSzhwWex2XTet3cg",
			AccessKeySecret:  "mMb6wb60fUtRtnxv43Y4eRc12HODjV",
			SignName:         "SignName",
			TemplateIDVerify: "TemplateIDVerify",
		},
		AllowedServers: &AllowedServers{Names: []string{}},
	}
}

func init() {
	flag.StringVar(&configFile, "c", "cmd/config-example.toml", "path of gsms config file.")
}

func overrideConfByEnvVars(config *Config) {
	EnvNsqd, ok := os.LookupEnv("NSQD_ADDRESS")
	if ok && EnvNsqd != "" {
		config.NSQAddr.NSQAddress = EnvNsqd
	}
}

// Init is func to initial log config
func Init() (err error) {
	Conf = NewConfig()
	viper.SetConfigFile(configFile)

	if err = viper.ReadInConfig(); err != nil {
		return err
	}

	if err = viper.Unmarshal(&Conf); err != nil {
		panic(fmt.Errorf("unable to decode into struct：%s ", err))
	}
	overrideConfByEnvVars(Conf)
	return nil
}
